//
// port_UNIX.cpp
// libprotea
// Tools Library for the Protea Project / Network port functionality, specific to UNIX
// Copyright (C) 2003, 2004, 2005 eXegeSys, Inc.
// Copyright (C) 2008 Bruce A. James
//
// This program is part of the Protea Project.
//
// The Protea Project is free software; you can redistribute it and/or modify it 
// under the terms of the GNU General Public License as published by the 
// Free Software Foundation, either version 3 of the License, or (at your 
// option) any later version.
//
// The Protea Project is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
// for more details.
// 
// You should have received a copy of the GNU General Public License along 
// with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Please send correspondence to:
// 
// theproteaproject@gmail.com
//

#include "../OS_defines.h"
#ifdef OS_UNIX

#include "../defines.h"
#include "port.h"
#include "../AppHandler/AppInterface.h"

XCPortHandler::~XCPortHandler() {
	Close();
};

void XCPortHandler::Init() {
	high_port = 0;
	FD_ZERO( &ports );
	Initialized = false;
};

void XCPortHandler::Create()
{
	INFUNC( XCPortHandler::Create, NULL );
	FD_ZERO( &ports );
	Initialized = true;
	OUTFUNC();
};

void XCPortHandler::Add( XCMsgPort* port )
{
	INFUNC( XCPortHandler::Add, NULL );

//	assert( port );
//	assert( port->transport );
//	cout << "Do FD_SET( " << port->transport->GetInHandle() << ", " << ports << ")" << endl;
	PORT_HANDLE input = port->transport->GetInHandle();
	FD_SET( (SOCKET)input, &ports);
	if ( (long)input > (long)high_port )
		high_port = input;

	OUTFUNC();
};
 
void XCPortHandler::Close() {
/*
	char temp[ 255 ];
	sprintf( temp, "Close completion port: %x", *ports );
	cout << temp << endl;
*/
	Init();
};

long XCPortHandler::Select( time_val* tv, XCMsgPort** result, int* reading )
{
	INFUNC( XCPortSelect, NULL );
	int returnval;
	returnval = XCSelectSocket( (PORT_HANDLE)high_port+1, (fd_set*)&ports, NULL, NULL, tv );
	OUTFUNCRET( returnval );
};

void XCPortHandler::Abort() {
};

#endif // OS_UNIX
